package cn.iocoder.yudao.module.book.service.images;

import cn.iocoder.yudao.module.book.controller.admin.records.vo.RecordsSaveReqVO;
import cn.iocoder.yudao.module.book.controller.app.bookcase.vo.AppBooksRespVO;
import cn.iocoder.yudao.module.book.controller.app.readBook.vo.AppbookImagesRespVO;
import cn.iocoder.yudao.module.book.dal.dataobject.records.RecordsDO;
import cn.iocoder.yudao.module.book.service.books.BooksService;
import cn.iocoder.yudao.module.book.service.records.RecordsService;
import cn.iocoder.yudao.module.book.service.users.userDTOService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.util.*;
import cn.iocoder.yudao.module.book.controller.admin.images.vo.*;
import cn.iocoder.yudao.module.book.dal.dataobject.images.bookImagesDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.book.dal.mysql.images.bookImagesMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.*;

/**
 * 绘本页 Service 实现类
 *
 * @author xi
 */
@Slf4j
@Service
@Validated
public class bookImagesServiceImpl implements bookImagesService {

    @Resource
    private bookImagesMapper bookImagesMapper;

    @Resource
    private RecordsService recordsService;

    @Resource
    private userDTOService userService;

    @Resource
    private BooksService bookService;


    @Override
    public Integer createbookImages(bookImagesSaveReqVO createReqVO) {
        // 计算顺序：无论前端是否传入，统一按该书(bookId)的最大顺序 + 1
        Integer bookId = createReqVO.getBookId();
        Integer maxOrder = 0;
        if (bookId != null) {
            maxOrder = bookImagesMapper.selectMaxOrderByBookId(bookId);
            if (maxOrder == null) {
                maxOrder = 0;
            }
        }
        Integer nextOrder = maxOrder + 1;

        // 插入
        bookImagesDO bookImages = BeanUtils.toBean(createReqVO, bookImagesDO.class);
        bookImages.setImageOrder(nextOrder);
        bookImagesMapper.insert(bookImages);
        // 返回
        return bookImages.getImageId();
    }

    @Override
    public void updatebookImages(bookImagesSaveReqVO updateReqVO) {
        // 校验存在
        validatebookImagesExists(updateReqVO.getImageId());
        // 更新
        bookImagesDO updateObj = BeanUtils.toBean(updateReqVO, bookImagesDO.class);
        bookImagesMapper.updateById(updateObj);
    }

    @Override
    public void deletebookImages(Integer id) {
        // 校验存在
        validatebookImagesExists(id);
        // 删除
        bookImagesMapper.deleteById(id);
    }

    private void validatebookImagesExists(Integer id) {
        if (bookImagesMapper.selectById(id) == null) {
            throw exception(BOOK_IMAGES_NOT_EXISTS);
        }
    }

    @Override
    public bookImagesDO getbookImages(Integer id) {
        return bookImagesMapper.selectById(id);
    }

    @Override
    public PageResult<bookImagesDO> getbookImagesPage(bookImagesPageReqVO pageReqVO) {
        return bookImagesMapper.selectPage(pageReqVO);
    }

    @Override
    public List<AppbookImagesRespVO> getBookImagesByBookId(@Valid Integer bookId) {
        // 先验证bookId是否有效
        if (bookId == null) {
            throw new IllegalArgumentException("书本ID不能为空");
        }
        
        // 获取书本信息，并检查是否存在
        AppBooksRespVO bookInfo = bookService.getByBookId(bookId, null);
        if (bookInfo == null) {
            log.error("书本不存在，bookId: {}", bookId);
            throw new IllegalArgumentException("书本不存在，ID: " + bookId);
        }
        
        // 创建阅读记录
        RecordsDO recordsDO = new RecordsDO();
        recordsDO.setBookId(bookId);
        recordsDO.setUserId(userService.getCurrentUserId());
        recordsDO.setCollectionId(bookInfo.getCollectionId());
        recordsDO.setReadingDate(LocalDate.now());
        recordsDO.setReadingCount(1);
        recordsDO.setReadingNotes("待添加");
        recordsDO.setDeleted(false);
        
        log.info("创建阅读记录: {}", recordsDO.toString());
        
        try {
            recordsService.createRecords(BeanUtils.toBean(recordsDO, RecordsSaveReqVO.class));
        } catch (Exception e) {
            log.warn("创建阅读记录失败，可能已存在: {}", e.getMessage());
            // 阅读记录创建失败不应该影响图片获取，继续执行
        }
        
        return bookImagesMapper.getBookImagesByBookId(bookId);
    }

    @Override
    public Boolean markRead(Integer bookId) {
        Long userId = userService.getCurrentUserId();

        // 查询是否已有阅读记录
        RecordsDO existingRecord = recordsService.getByUserIdAndBookId(userId, bookId);

        if (existingRecord != null) {
            // 更新已读状态
            existingRecord.setReadingCount(existingRecord.getReadingCount() + 1);
            existingRecord.setReadingDate(LocalDate.now());
            RecordsSaveReqVO updateReqVO = BeanUtils.toBean(existingRecord, RecordsSaveReqVO.class);
//            updateReqVO.setReadingDate(LocalDate.now().atStartOfDay()); // 转换为LocalDateTime
            recordsService.updateRecords(updateReqVO);
        } else {
            // 创建新的阅读记录
            AppBooksRespVO book = bookService.getByBookId(bookId, null);
            if (book == null || book.getCollectionId() == null) {
                throw exception(BOOK_NOT_EXISTS);
            }

            RecordsSaveReqVO createReqVO = new RecordsSaveReqVO();
            createReqVO.setBookId(bookId);
            createReqVO.setUserId(userId.intValue());
            createReqVO.setCollectionId(book.getCollectionId());
            createReqVO.setReadingDate(LocalDate.now().atStartOfDay()); // 使用LocalDateTime
            createReqVO.setReadingCount(1);
            createReqVO.setReadingNotes("已读");
            createReqVO.setDeleted(false);
            recordsService.createRecords(createReqVO);
        }

        return true;
    }

//    @Override
//    public Boolean markRead(Integer bookId) {
//        RecordsDO recordsDO = recordsService.selectByBookId(bookId);
//    }

}